import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

// 全局样式重置（清除默认边距）
const globalStyles = `
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
  }
  html, body, #root {
    height: 100%;
    overflow: hidden;
  }
`;

// API基础路径（Spring Boot后端地址）
const API_BASE_URL = 'http://localhost:8080/api/products';

const Dashboard = () => {
  // 注入全局样式
  useEffect(() => {
    const style = document.createElement('style');
    style.innerHTML = globalStyles;
    document.head.appendChild(style);
    return () => document.head.removeChild(style);
  }, []);

  const navigate = useNavigate();
  // 状态管理
  const [manufacturers, setManufacturers] = useState([]);
  const [standards, setStandards] = useState([]);
  const [models, setModels] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [selectedMfr, setSelectedMfr] = useState(null);
  const [expandedModels, setExpandedModels] = useState([]);
  const [selectedModel, setSelectedModel] = useState(null);
  const [filterLoading, setFilterLoading] = useState(false);

  // 从localStorage获取登录token
  const getToken = () => localStorage.getItem('token');

  // 退出登录
  const handleLogout = () => {
    localStorage.removeItem('token');
    navigate('/login');
  };

  // 切换型号展开/折叠
  const toggleModel = (modelId) => {
    setExpandedModels(prev => 
      prev.includes(modelId) 
        ? prev.filter(id => id !== modelId) 
        : [...prev, modelId]
    );
  };

  // 合并的获取型号数据函数（适配后端筛选逻辑）
  const fetchModels = async (mfrId = null) => {
    const token = getToken();
    if (!token) {
      handleLogout();
      return;
    }
    
    try {
      if (mfrId !== null) setFilterLoading(true);
      
      const config = {
        headers: { 'Authorization': `Bearer ${token}` },
        params: mfrId !== null ? { mfrId } : {}
      };
      
      // 后端已返回包含子型号的完整数据，前端直接接收
      const res = await axios.get(`${API_BASE_URL}/models`, config);
      console.log("聯想的型号数据：", res.data); // 确认res.data是否有值
      setModels(res.data);
    } catch (err) {
      setError('数据加载失败，请重试');
      console.error('请求失败：', err);
      if (err.response?.status === 401) {
        handleLogout();
      }
    } finally {
      setFilterLoading(false);
    }
  };

  // 请求后端数据
  useEffect(() => {
    const fetchData = async () => {
      const token = getToken();
      if (!token) {
        handleLogout();
        return;
      }
      
      try {
        const config = {
          headers: { 'Authorization': `Bearer ${token}` }
        };

        // 并行请求制造商和标准数据
        const [mfrRes, stdRes] = await Promise.all([
          axios.get(`${API_BASE_URL}/manufacturers`, config),
          axios.get(`${API_BASE_URL}/standards`, config)
        ]);

        setManufacturers(mfrRes.data);
        setStandards(stdRes.data);
        await fetchModels(); // 初始加载所有型号（含子型号）
        setLoading(false);
      } catch (err) {
        setError('数据加载失败，请重试');
        setLoading(false);
        console.error('请求失败：', err);
        if (err.response?.status === 401) {
          handleLogout();
        }
      }
    };

    fetchData();
  }, []);

  // 筛选型号（依赖后端返回包含子型号的结果）
  useEffect(() => {
    if (!loading && manufacturers.length > 0) {
      fetchModels(selectedMfr);
    }
  }, [selectedMfr]);

  // 根据ID查找制造商名称（适配后端子型号继承的mfrId）
  const getManufacturerName = (mfrId) => {
    // 后端已为子型号设置mfrId，直接查找即可
    return manufacturers.find(m => m.id === mfrId)?.name || '未知制造商';
  };

  // 根据ID查找标准名称
  const getStandardName = (stdId) => {
    return standards.find(s => s.id === stdId)?.name || '无标准';
  };

  // 查找子型号（前端仅做展示层筛选，实际数据已由后端返回）
  const getChildModels = (parentId) => {
    return models.filter(model => model.pId === parentId);
  };

  // 递归渲染型号树（展示所有层级子型号）
  const renderModelTree = (parentId = null, level = 0) => {
    // 筛选出属于当前制造商且父ID匹配的型号
    const children = parentId === null 
      ? models.filter(model => 
          // 顶级节点：要么pId=null，要么父型号不在当前筛选结果中
          (model.pId === null || !models.some(m => m.id === model.pId))
        )
      : getChildModels(parentId);
   // 子型号

    if (children.length === 0) return null;

    return (
      <ul style={{ 
        listStyle: 'none', 
        paddingLeft: `${level * 20}px`, 
        margin: '5px 0'
      }}>
        {children.map(model => (
          <li key={model.id} style={{ margin: '8px 0' }}>
            <div 
              style={{
                padding: '8px 12px',
                borderRadius: '4px',
                backgroundColor: selectedModel?.id === model.id ? '#e6f7ff' : '#f5f5f5',
                cursor: 'pointer',
                borderLeft: `3px solid ${selectedModel?.id === model.id ? '#1890ff' : 'transparent'}`,
                transition: 'all 0.2s'
              }}
              onClick={() => setSelectedModel(model)}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                {/* 有子型号则显示展开/折叠按钮 */}
                {getChildModels(model.id).length > 0 && (
                  <span 
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleModel(model.id);
                    }}
                    style={{ cursor: 'pointer' }}
                  >
                    {expandedModels.includes(model.id) ? '▼' : '►'}
                  </span>
                )}
                <span style={{ fontWeight: level === 0 ? 'bold' : 'normal' }}>
                  {model.name}
                </span>
                {/* 显示标准标签 */}
                {model.stdId && (
                  <span style={{
                    fontSize: '12px',
                    backgroundColor: '#fff3cd',
                    color: '#856404',
                    padding: '2px 6px',
                    borderRadius: '12px'
                  }}>
                    {getStandardName(model.stdId)}
                  </span>
                )}
                {/* 显示制造商标签（子型号也会正确显示） */}
                {model.mfrId && (
                  <span style={{
                    fontSize: '12px',
                    backgroundColor: '#e6f7ff',
                    color: '#1890ff',
                    padding: '2px 6px',
                    borderRadius: '12px',
                    marginLeft: '8px'
                  }}>
                    {getManufacturerName(model.mfrId)}
                  </span>
                )}
              </div>
            </div>
            {/* 递归渲染子型号 */}
            {expandedModels.includes(model.id) && renderModelTree(model.id, level + 1)}
          </li>
        ))}
      </ul>
    );
  };

  // 加载中/错误状态展示
  if (loading) {
    return (
      <div style={{ 
        height: '100vh',
        backgroundColor: '#f0f2f5',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}>
        加载中...
      </div>
    );
  }
  if (error) {
    return (
      <div style={{ 
        height: '100vh',
        backgroundColor: '#f0f2f5',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: 'red'
      }}>
        {error}
      </div>
    );
  }

  return (
    <div style={{ 
      height: '100vh',
      width: '100vw', 
      display: 'flex',
      flexDirection: 'column',
      backgroundColor: '#f0f2f5'
    }}>
      {/* 顶部导航栏 */}
      <header style={{
        height: '60px',
        backgroundColor: 'white',
        padding: '0 30px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
        flexShrink: 0
      }}>
        <div style={{ fontSize: '20px', fontWeight: 'bold', color: '#1890ff' }}>
          产品型号管理
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
          <span style={{ color: '#666' }}>欢迎回来！</span>
          <button
            onClick={handleLogout}
            style={{
              padding: '6px 12px',
              backgroundColor: '#fff',
              color: '#ff4d4f',
              border: '1px solid #ff4d4f',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            退出登录
          </button>
        </div>
      </header>

      {/* 主体内容区 */}
      <main style={{
        flexGrow: 1,
        display: 'flex',
        padding: '20px',
        overflow: 'hidden'
      }}>
        {/* 左侧筛选区 */}
        <div style={{
          width: '250px',
          backgroundColor: 'white',
          borderRadius: '8px',
          padding: '20px',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
          marginRight: '20px',
          display: 'flex',
          flexDirection: 'column',
          flexShrink: 0
        }}>
          <h3 style={{ margin: '0 0 15px', color: '#333' }}>制造商筛选</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
            <button
              onClick={() => setSelectedMfr(null)}
              style={{
                padding: '8px 12px',
                textAlign: 'left',
                backgroundColor: selectedMfr === null ? '#1890ff' : '#f5f5f5',
                color: selectedMfr === null ? 'white' : '#333',
                border: 'none',
                borderRadius: '4px',
                cursor: 'pointer'
              }}
            >
              全部制造商
            </button>
            {manufacturers.map(mfr => (
              <button
                key={mfr.id}
                onClick={() => setSelectedMfr(mfr.id)}
                style={{
                  padding: '8px 12px',
                  textAlign: 'left',
                  backgroundColor: selectedMfr === mfr.id ? '#1890ff' : '#f5f5f5',
                  color: selectedMfr === mfr.id ? 'white' : '#333',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                {mfr.name}
              </button>
            ))}
          </div>

          <div style={{ marginTop: '30px' }}>
            <h3 style={{ margin: '0 0 15px', color: '#333' }}>产品标准</h3>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
              {standards.map(std => (
                <li key={std.id} style={{
                  padding: '8px 12px',
                  backgroundColor: '#f5f5f5',
                  borderRadius: '4px',
                  marginBottom: '8px'
                }}>
                  {std.name}
                </li>
              ))}
            </ul>
          </div>
        </div>

        {/* 右侧内容区 */}
        <div style={{ 
          flexGrow: 1,
          overflow: 'auto',
          paddingBottom: '20px'
        }}>
          <div style={{
            backgroundColor: 'white',
            borderRadius: '8px',
            padding: '20px',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
            marginBottom: '20px'
          }}>
            <h2 style={{ margin: '0 0 20px', color: '#333' }}>
              {selectedMfr ? `${getManufacturerName(selectedMfr)} 产品型号` : '全部产品型号'}
            </h2>
            {filterLoading ? (
              <div>筛选中...</div>
            ) : models.length === 0 ? (
              <div>暂无型号数据</div>
            ) : (
              renderModelTree()
            )}
          </div>

          {/* 型号详情（子型号也会正确显示制造商） */}
          {selectedModel && (
            <div style={{
              backgroundColor: 'white',
              borderRadius: '8px',
              padding: '20px',
              boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
            }}>
              <h3 style={{ margin: '0 0 15px', color: '#333' }}>
                型号详情：{selectedModel.name}
              </h3>
              <div style={{ lineHeight: '1.6', color: '#666' }}>
                <p>
                  <span style={{ fontWeight: 'bold', color: '#333' }}>所属制造商：</span>
                  {getManufacturerName(selectedModel.mfrId)}
                </p>
                <p>
                  <span style={{ fontWeight: 'bold', color: '#333' }}>遵循标准：</span>
                  {getStandardName(selectedModel.stdId)}
                </p>
                {selectedModel.ref && (
                  <p>
                    <span style={{ fontWeight: 'bold', color: '#333' }}>参考链接：</span>
                    <a 
                      href={selectedModel.ref} 
                      target="_blank" 
                      rel="noopener noreferrer"
                      style={{ color: '#1890ff', textDecoration: 'underline' }}
                    >
                      查看规格详情
                    </a>
                  </p>
                )}
                <p>
                  <span style={{ fontWeight: 'bold', color: '#333' }}>父型号：</span>
                  {selectedModel.pId 
                    ? models.find(m => m.id === selectedModel.pId)?.name || '无'
                    : '无'
                  }
                </p>
              </div>
            </div>
          )}
        </div>
      </main>

      {/* 页脚 */}
      <footer style={{
        height: '50px',
        textAlign: 'center',
        lineHeight: '50px',
        color: '#666',
        fontSize: '14px',
        borderTop: '1px solid #e8e8e8',
        backgroundColor: 'white',
        flexShrink: 0
      }}>
        © 2025 产品型号管理
      </footer>
    </div>
  );
};

export default Dashboard;